'use strict';
var ksrCustomerEvent = angular.module('ksrCustomerEvent',[
    'ngCookies'
    ,'ngRoute'
    ,'ui.bootstrap'
    ,'ksr.filters'
    ,'ksr.services'
    ,'ksr.directives'
]);

ksrCustomerEvent.config(['$routeProvider','$locationProvider',
    function($routeProvider,$locationProvider){
		$routeProvider.
		when("/event",{
			templateUrl:'/ksr/partials/customer/event.htm'
				,controller:"customerEventCtrl"
		}).
		otherwise({
			redirectTo:'/event'
		});
	}
]);

/*controller*/
ksrCustomerEvent.controller('customerEventCtrl', ['$scope','$rootScope','$routeParams','$modal','$sce','$route','$timeout','jsonSvc','ksrCacheSvc',
	 function($scope,$rootScope,$routeParams,$modal,$sce,$route,$timeout,jsonSvc,ksrCacheSvc) {
	   console.log("customerEventCtrl");
	   $scope.alerts = [];
	    $scope.closeAlert = function(index) {
		    $scope.alerts.splice(index, 1);
		  };
		jsonSvc.getList({entityType:'customer',type:'event-schedule',eid:id}).$promise.then(function(data){
			$scope.eventScheduleList = data;
			$scope.event=data[0].event;
			jsonSvc.getList({entityType:'customer',type:'event-subscription',param1:$scope.event.id}).$promise.then(function(data){
				$scope.subscribeList=data;
			})
		});
			ksrCacheSvc.get("customer",false).then(function(data){
				if (data.id){
		    	$scope.customer = data;
				}
	    })
		$scope.isSubscribed=function(scheduleId,addressId){
			var subscribed=false;
			angular.forEach($scope.subscribeList, function(subscription){
				if (subscription.eventSchedule.id===scheduleId&&subscription.address.id===addressId){
					subscribed=true;
				}
			});
			return subscribed;
		}
		//modal
    var modalInstance;
		$scope.subscribeEvent=function(idx,addressIdx,mode){
			modalInstance = $modal.open({
              templateUrl: '/ksr/partials/customer/subscription-modal.htm',
              scope:$scope,
              size:"lg"
              ,
              resolve: {
                subscription: function () {
                	$scope.mode=mode;
                	if (mode==="create"){
                        $scope.subscription={};
                        $scope.subscription.subscriptionType=$scope.eventScheduleList[idx].scheduleType;
                        $scope.subscription.customer = $scope.customer;
                        $scope.subscription.eventSchedule = $scope.eventScheduleList[idx];
                        $scope.subscription.address = $scope.eventScheduleList[idx].eventAddresses[addressIdx];
                	} else {//edit
                		$scope.subscription={};
                		angular.copy($scope.subscribeList[idx],$scope.subscription);
                	}

                  // return scope.match;
                }
              }
            });
		};
		$scope.cancel = function () {
			$scope.subscription={};
	        modalInstance.dismiss('cancel');
	      };
    	$scope.submit=function(){
    		jsonSvc.saveItem({entityType:"customer",type:"event-subscription"},$scope.subscription).$promise.then(function(data){
				console.log("udpate customer subscription status:"+data.status);
	            if ($scope.mode==="create"){
	            	$scope.subscribeList.push($scope.subscription);
	            }
	    		$scope.subscription={};
			});
			console.log("mode="+$scope.mode);
            modalInstance.close();
        }   

           $scope.cancelSubscription=function(subIdx){
	         	// $modal.open();
	     		modalInstance = $modal.open({templateUrl: '/ksr/partials/confirmModal.htm'});
			    $rootScope.description = "undescribe the subscription";
			    $rootScope.yes = function () {
			        modalInstance.close("yes");
			    };
			    $rootScope.no = function () {
			        modalInstance.dismiss('cancel');
			    };

	    modalInstance.result.then(function () {
			if (id>=0){
				console.log("cancel subscription,idx="+subIdx);
				jsonSvc.removeItemBy({entityType:"customer",type:"event-subscription"},$scope.subscribeList[subIdx]).$promise.then(function(data){
					if (data.status==="ok"){
						console.log("unscribe subscription successfully");
						$scope.subscribeList.splice(subIdx,1);
					} else {
						console.error("unscribe subscription! Error:"+data.errMsg);
						$scope.alerts.push({type:'danger', msg:$sce.trustAsHtml('Fail to unscribe subscription! Please try again later!')});
					}
				});
			}
	    }, function () {
	      console.log('user cancel the unscribe action! idx='+subIdx);
	    });  
	    }
 }]);
